package com.xiaobingby.config.exception;

import com.xiaobingby.common.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * Author: XiaoBingBy
 * Email: XiaoBingBy@qq.com
 * Date: 2017/9/1
 * Time: 00:00
 * Describe: 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理Shiro注解跳转
     * @param request
     * @param response
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = org.apache.shiro.authz.UnauthorizedException.class)
    public ModelAndView authzErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
//        response.sendRedirect("/500.html");
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", request.getRequestURL());
        mav.setViewName("/admin/403");
        return mav;
    }

    /**
     * mysql数据库字段唯一异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public JsonResult handleMySQLIntegrityConstraintViolationException(HttpServletRequest request,Exception e) {
        String unique = request.getParameter("unique");
        log.error(unique+"重复："+e.getMessage());
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus("400");
        result.setMsg(unique+"重复");
        return result;
    }

    /**
     * @Validate 校验方法参数
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public JsonResult resolveConstraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder strBuilder = new StringBuilder();
        for (ConstraintViolation<?> violation : violations ) {
            strBuilder.append(violation.getMessage() + "\n");
        }
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setMsg(strBuilder.toString());
        return result;
    }

    /**
     * @Valid 校验bean
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public JsonResult exception(BindException e) {
        StringBuilder msgBuilder = new StringBuilder();
        for (ObjectError item : e.getAllErrors()) {
            msgBuilder.append(item.getDefaultMessage()).append("\n");
        }
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setMsg(msgBuilder.toString());
        return result;
    }
}
